package gnss

import (
	"fmt"
	"math"
)

/**
  钟差改正
  msgid: 1058(GPS), 1064(GLO)
*/

type IgmasSsrClkCorrectionSat struct {
	Satid uint8
	C0    float64
	C1    float64
	C2    float64
}

func (this *IgmasSsrClkCorrectionSat) String() string {
	return fmt.Sprintf("SatId:%d, C0:%.4f, C1:%.6f, C2:%.8f", this.Satid, this.C0, this.C1, this.C2)
}

func EncodeIgmasSsrClkCorrection(head *IgmasSsrCorrectionHead, lst []*IgmasSsrClkCorrectionSat, outBuf []byte, startBitN int) (bitN int) {

	bitN = EncodeIgmasSsrHead(head, outBuf, startBitN, len(lst))

	for i := 0; i < len(lst); i++ {
		itm := lst[i]
		SetBitU8(outBuf, bitN, 6, itm.Satid)
		bitN += 6

		SetBitI32(outBuf, bitN, 22, int32(math.Round(itm.C0/1e-4)))
		bitN += 22

		SetBitI32(outBuf, bitN, 21, int32(math.Round(itm.C1/1e-6)))
		bitN += 21

		SetBitI32(outBuf, bitN, 27, int32(math.Round(itm.C2/2e-8)))
		bitN += 27
	}

	return
}

func DecodeIgmasSsrClkCorrection(inBuf []byte, startBitN int) (head *IgmasSsrCorrectionHead, lst []*IgmasSsrClkCorrectionSat, bitN int) {
	head = &IgmasSsrCorrectionHead{}
	bitN, n := DecodeIgmasSsrHead(head, inBuf, startBitN)

	lst = make([]*IgmasSsrClkCorrectionSat, n)
	for i := 0; i < len(lst); i++ {
		itm := &IgmasSsrClkCorrectionSat{}
		lst[i] = itm
		itm.Satid = GetBitU8(inBuf, bitN, 6)
		bitN += 6

		itm.C0 = float64(GetBitI32(inBuf, bitN, 22)) * 1e-4
		bitN += 22

		itm.C1 = float64(GetBitI32(inBuf, bitN, 21)) * 1e-6
		bitN += 21

		itm.C2 = float64(GetBitI32(inBuf, bitN, 27)) * 2e-8
		bitN += 27

	}

	return
}
